package com.CityHunter.Activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.CityHunter.R;
import com.CityHunter.RoutePoint;

public class RouteAct extends Activity{
	TextView tv;
	List<RoutePoint> rpList = new ArrayList<RoutePoint>();
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.route_test);
		HttpPost httpRequest = new HttpPost("http://maps.google.com.hk/maps/api/directions/json?origin=22.312413,114.226736&destination=22.320468,114.221477&sensor=false&mode=walking&language=zh-TW");
		DefaultHttpClient httpclient = new DefaultHttpClient();
		tv=(TextView)findViewById(R.id.route_tv);
			// get response
			HttpResponse httpResponse = null;
			try {
				httpResponse = httpclient.execute(httpRequest);
				String strResult = EntityUtils.toString(httpResponse.getEntity());
				tv.setText("NOthing");
				JSONObject result=new JSONObject(strResult);
				
				JSONArray routes=result.getJSONArray("routes");
				JSONObject routesObj=routes.getJSONObject(0);
				JSONArray legs=routesObj.getJSONArray("legs");
				JSONArray steps=legs.getJSONObject(0).getJSONArray("steps");
				String desc="";
				for(int i=0;i<steps.length();i++){
					JSONObject start_location=steps.getJSONObject(i).getJSONObject("start_location");
					JSONObject end_location=steps.getJSONObject(i).getJSONObject("end_location");
					
					desc=steps.getJSONObject(i).getString("html_instructions")+"\n";
					rpList.add(new RoutePoint(Double.valueOf(end_location.getString("lat")), Double.valueOf(end_location.getString("lng")), descriptionParser(desc)) );
				}
				tv.setText(rpList.get(0).getDescription());
			} 
			catch(Exception e){
				Log.e("Error",e.toString());
				Toast.makeText(this, e.toString(), Toast.LENGTH_LONG);
			}
			// if connection status is OK
			
}
	
	public String descriptionParser(String result){
		String clear="";
		boolean ok=true;
		for(int ind=0;ind<result.length();ind++){
			if (result.charAt(ind)=='<')
				ok=false;
			else if(result.charAt(ind)=='>')
				ok=true;
			else if(ok==true)
				clear+=result.charAt(ind);
				
		}
		return clear;
	}
}